package Servlet.Add;

import Server.Add.novelServer;
import bean.userBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/novelAddDo")
public class novelAddDo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//由于新添商品的表单是以POST方式提交的，理应访问doPost()方法，
		//所以，如果以GET方式访问此Servlet，即访问doGet()方法，那么request中应无表单内容，
		//故此处需返回到Servlet类GoodsAdd，以便在表单输入新的商品信息。
		response.sendRedirect("GoodsAdd");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");		
		java.io.PrintWriter out = response.getWriter();
		String msg = "";
		String url = "GoodsShow";
		
		try {
			HttpSession session = request.getSession();
			userBean user= (userBean) session.getAttribute("user");
			if (user == null || !user.getUserType().equals("admin")) {							//如果登录已失效，或权限不足
				msg = "图片没有更新。您的登录已失效。";
				msg += "（<a href='login.jsp' target='_top'>用户登录</a>）</p>";	//前往最外层的框架集，即整个浏览器窗口
				return;
			}
			
			novelServer server = new novelServer();			
			String novelNumber = server.insert(request);

			if (novelNumber.equals("0")) {						//新添失败
				url = "";
				return;
			}
		
			//----------------------- 新添成功
			url = "novelInfoServlet?novelNumber=" + novelNumber;			//目标网址
			url = "@Redirect:" + url;						//增加@Redirect用于通知Ajax进行网页转向（自创协议）
			
		} catch (Exception e) {
			msg += "系统发生错误。";	
			e.printStackTrace();
		} finally {
			if (request.getAttribute("msg") != null) {
				msg += request.getAttribute("msg").toString();
			}
			request.setAttribute("msg", msg);

			//----由于页面goodsAdd.jsp中是以Ajax方式提交表单，所以无论是输出错误消息，
			//----还是新添成功需跳转到详情页面，这里都是调用out()方法输出内容，
			//----再由Ajax根据接收到的内容决定下一步如何处理。
			if (url.equals("")) {							//如果新添失败
				out.print(msg);								//输出错误消息
			} else {
				out.print(url);								//网页将转向。
			}
		}
	}
}
